package cn.edu.zime.tjh.client;

import cn.edu.zime.tjh.handler.AsyncClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.function.Consumer;

public class AsyncEchoClient {
    private EventLoopGroup group;
    private Channel channel;
    private boolean isConnected = false;
    
    private Consumer<String> messageCallback;
    private Consumer<String> statusCallback;
    
    public AsyncEchoClient(Consumer<String> messageCallback, Consumer<String> statusCallback) {
        this.messageCallback = messageCallback;
        this.statusCallback = statusCallback;
    }
    
    public void connect(String host, int port) throws Exception {
        group = new NioEventLoopGroup();
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());
                            p.addLast(new AsyncClientHandler(messageCallback, statusCallback));
                        }
                    });
            
            ChannelFuture f = b.connect(host, port).sync();
            channel = f.channel();
            isConnected = true;
            
            if (statusCallback != null) {
                statusCallback.accept("Connected to " + host + ":" + port);
            }
            
        } catch (Exception e) {
            disconnect();
            throw e;
        }
    }
    
    public void sendMessage(String message) {
        if (isConnected && channel != null && channel.isActive()) {
            channel.writeAndFlush(message);
        } else {
            if (statusCallback != null) {
                statusCallback.accept("Not connected to server");
            }
        }
    }
    
    public void disconnect() {
        isConnected = false;
        
        if (channel != null && channel.isActive()) {
            channel.close();
        }
        
        if (group != null) {
            group.shutdownGracefully();
        }
        
        if (statusCallback != null) {
            statusCallback.accept("Disconnected");
        }
    }
    
    public boolean isConnected() {
        return isConnected && channel != null && channel.isActive();
    }
    
    public void waitForDisconnection() throws InterruptedException {
        if (channel != null) {
            channel.closeFuture().sync();
        }
    }
}